package net.gyapp.markim.module.basic;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;

import com.easyder.wrapper.base.adapter.TabAdapter;
import com.easyder.wrapper.base.view.WrapperMvpActivity;
import com.easyder.wrapper.base.view.WrapperMvpFragment;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.utils.LogUtils;
import com.xuhao.android.libsocket.utils.ActivityStack;
import com.xuhao.android.libsocket.utils.Logger;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.core.entity.MessageEntity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.event.MessageChanged;
import net.gyapp.markim.module.basic.event.MessageIml;
import net.gyapp.markim.module.basic.event.ResponseChanged;
import net.gyapp.markim.module.basic.event.ResponseIml;
import net.gyapp.markim.module.basic.event.TabChanged;
import net.gyapp.markim.module.collect.CollectFragment;
import net.gyapp.markim.module.contact.ContactsFragment;
import net.gyapp.markim.module.message.MessageFragment;
import net.gyapp.markim.module.mine.MineFragment;
import net.gyapp.markim.module.mine.vo.MemberListVo;
import net.gyapp.markim.testing.TestListActivity;
import net.gyapp.markim.utils.NotificationUtils;
import net.gyapp.markim.utils.NotifyUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.leolin.shortcutbadger.ShortcutBadger;
import me.winds.widget.cluster.tabbar.OnSimpleTabSelectedListener;
import me.winds.widget.cluster.tabbar.RealizeTabItem;
import me.winds.widget.cluster.tabbar.TabBar;
import me.winds.widget.usage.TitleView;

public class MainActivity extends WrapperMvpActivity<CommonPresenter> {

    @BindView(R.id.mViewPager)
    ViewPager pager;
    @BindView(R.id.mTabBar)
    TabBar mTabBar;

    private TabAdapter adapter;
    NotificationUtils notification;

    public static Intent getIntent(Context context) {
        return new Intent(context, MainActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }


    @Override
    protected int getViewLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        notification = new NotificationUtils(MainActivity.this);
        initTab();
    }


    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if(url.contains(ApiConfig.API_LIST_USER_FRIENDS)) {
            processMemberList((MemberListVo)dataVo);
        }
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    protected int getTitleState() {
        return TITLE_NONE;
    }

    @Override
    public void onBackPressedSupport() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    @Subscribe
    public void messageChanged(MessageChanged changed) {
        if (changed.sign == MessageIml.SIGN_CONVERSATION_REFRESH) {
            onPauseMessageReceive();
        }
    }

    @Subscribe
    public void updateFriend(ResponseChanged changed) {
        if(changed.sign == ResponseIml.SIGN_PROCESS_LOGIN_RESPONSE_SUCCESS_UPDATE_FRIEND) {
            getFriendList();
        }
    }

    /**
     * 当应用非在主界面时回调
     */
    private void onPauseMessageReceive() {
        if (ActivityStack.isBackground()) {
            LogUtils.info("--> Receiver 内部通知");
            List<MessageEntity> list = ImHelper.getLatestMessage();
            if(list != null && list.size() > 0) {
                MessageEntity entity = list.get(0);
                Intent intent = new Intent(mActivity, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                PendingIntent pIntent = PendingIntent.getActivity(mActivity,
                        1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                new NotifyUtil(mActivity, 1001).notify_normal_singline(pIntent, R.mipmap.icon, entity.content, getString(R.string.app_name),
                        entity.content, true, true, false);
            }
        }
    }

    /**
     * 初始化tab
     */
    private void initTab() {
        List<WrapperMvpFragment> list = getFragments();
        adapter = new TabAdapter(getSupportFragmentManager(), list);
        pager.setAdapter(adapter);
        pager.setOffscreenPageLimit(list.size());
        initTabBar();
    }

    private void initTabBar() {
        mTabBar.addItem(new RealizeTabItem(mActivity).init(R.drawable.selector_tab_msg, "消息"))
                .addItem(new RealizeTabItem(mActivity).init(R.drawable.selector_tab_contact, "通讯录"))
                .addItem(new RealizeTabItem(mActivity).init(R.drawable.selector_tab_collect, "收藏"))
                .addItem(new RealizeTabItem(mActivity).init(R.drawable.selector_tab_me, "我的"));
        mTabBar.setOnTabSelectedListener(new OnSimpleTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                pager.setCurrentItem(position, false);
                EventBus.getDefault().post(new TabChanged(position));
            }

            @Override
            public void onTabReSelected(int position) {
                super.onTabReSelected(position);
                switch (position) {
                    case 0:

                        break;
                    case 1:

                        break;

                }
            }
        });
    }

    private void getFriendList() {
        Logger.i("获取用户数据");
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_LIST_USER_FRIENDS, MemberListVo.class);
    }

    /**
     * 获取tab页面
     *
     * @return
     */
    private List<WrapperMvpFragment> getFragments() {
        List<WrapperMvpFragment> list = new ArrayList<>();
        list.add(MessageFragment.newInstance());
        list.add(ContactsFragment.newInstance());
        list.add(CollectFragment.newInstance());
        list.add(MineFragment.newInstance());
        return list;
    }


    /**
     * 设置角标文字
     *
     * @param index
     * @param num
     */
    public void setBedgeText(int index, int num) {
        mTabBar.getItem(index).setMessage(num);
        ShortcutBadger.applyCount(mActivity, num > 0 ? num : 0);
    }

    /**
     * 设置角标红点
     *
     * @param index
     * @param visible
     */
    private void setBadgeDot(int index, boolean visible) {
        mTabBar.getItem(index).setDot(visible);
    }


    private void processMemberList(MemberListVo dataVo) {
        ImHelper.updateOrInsertUser(dataVo.userFriends);
    }
}
